import { createRouter, createWebHistory } from 'vue-router'
import store from './store'
import axios from './libs/axios'

const base = process.env.NODE_ENV === 'production' ? '/vue3-ts-post/' : '/'

const routerHistory = createWebHistory(base)

const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('./views/Home.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('./views/Login.vue'),
      meta: {
        redirectAlreadyLogin: true
      }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('./views/Register.vue'),
      meta: {
        redirectAlreadyLogin: true
      }
    },
    {
      path: '/column/:id',
      name: 'column',
      component: () => import('./views/ColumnDetail.vue')
    },
    {
      path: '/create',
      name: 'create',
      component: () => import('./views/CreatePost.vue'),
      meta: {
        requiredLogin: true
      }
    },
    {
      path: '/edit/:id',
      name: 'edit',
      component: () => import('./views/EditPost.vue'),
      meta: {
        requiredLogin: true
      }
    },
    {
      path: '/post/:id',
      name: 'post',
      component: () => import('./views/PostDetail.vue')
    }
  ]
})

router.beforeEach((to) => {
  const { user, token } = store.state
  const { redirectAlreadyLogin, requiredLogin } = to.meta

  if (!user.isLogin) {
    if (!token) {
      if (requiredLogin) {
        return {
          name: 'login'
        }
      }
    } else {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      store.dispatch('fetchCurrentUser').then(() => {
        if (redirectAlreadyLogin) {
          return {
            name: 'home'
          }
        }
      }).catch(() => {
        // 获取当前登录用户信息出错，可能是网络问题，接口问题或 token 已过期
        // 因此执行一次 logout 操作后退出到登录页面
        store.commit('logout')
        return {
          name: 'login'
        }
      })
    }
  } else {
    if (redirectAlreadyLogin) {
      return {
        name: 'home'
      }
    }
  }
})

export default router
